/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.mathml_canonicalizator;

import java.util.*;

/**
 *
 * @author ziky
 */
public class MfencedTransformer implements Transformer {

    private Node root;
    private Node operators;
    private String openMode;
    private String closeMode;
    private int operatorsCount;

    public MfencedTransformer(String tagName, Map<String, String> attrs,
            Map<String, List<String>> properties) {

        operatorsCount = 0;

        List<String> attr_keep = properties.get("attr_keep") != null
                ? properties.get("attr_keep") : new ArrayList<String>();

        //special case, processing atrs open and close:
        if (attrs.containsKey("open")) {
            openMode = attrs.get("open");
        } else {
            openMode = "(";
        }

        if (attrs.containsKey("close")) {
            closeMode = attrs.get("close");
        } else {
            closeMode = ")";
        }

        //FIXME:is this really necessary? Is there any case we 
        //      want to keep any attributes?
        Util.removeAtrributes(attrs, attr_keep);

        root = new NodeImpl("mrow", attrs);
        operators = new NodeImpl("mrow", new HashMap<String, String>());
    }

    @Override
    public void addChild(Node n) {
        if (operatorsCount == 0) {
            if (n.getTagName().equals("mrow")) {
                operators = n;
                return;
            }
        }
        if (operatorsCount > 0) {
            Node comma = new NodeImpl("mo", new HashMap<String, String>());
            comma.setTextContent(",");
            operators.addChild(comma);
        }
        operators.addChild(n);
        operatorsCount++;
    }

    @Override
    public void setTextContent(String s) {
    }

    @Override
    public Node transform() {
        Node open = new NodeImpl("mo", new HashMap<String, String>());
        open.setTextContent(openMode);
        Node close = new NodeImpl("mo", new HashMap<String, String>());
        close.setTextContent(closeMode);

        root.addChild(open);
        root.addChild(operators);
        root.addChild(close);

        return root;
    }
}
